package com.why.cachecloud.web.controller;

import cn.hutool.crypto.SecureUtil;
import com.why.cachecloud.configuration.constant.AppCheckEnum;
import com.why.cachecloud.configuration.constant.AppUserTypeEnum;
import com.why.cachecloud.entity.AppAudit;
import com.why.cachecloud.entity.AppUser;
import com.why.cachecloud.util.ConstUtils;
import com.why.cachecloud.web.enums.SuccessEnum;
import com.why.cachecloud.web.util.AppDingTalkUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

/**
 * 用户信息管理
 *
 * @Author why
 * @Time 2014年6月6日
 */
@Controller
@RequestMapping("manage/user")
public class UserManageController extends BaseController {

    @Resource
    private AppDingTalkUtil appDingTalkUtil;

    /**
     * 用户初始化
     *
     * @param id 用户id
     * @return
     */
    @RequestMapping(value = "/init")
    public ModelAndView doUserInit(Model model, Long id) {
        if (id != null) {
            AppUser user = userService.get(id);
            model.addAttribute("user", user);
            model.addAttribute("modify", true);
        }
        return new ModelAndView("manage/user/initUser");
    }

    /**
     * 更新用户
     *
     * @param name
     * @param chName
     * @param email
     * @param mobile
     * @param password
     * @param type
     * @param userId
     * @return
     */
    @RequestMapping(value = "/add")
    public ModelAndView doAddUser(HttpServletResponse response, String name, String chName, String email, String mobile, String password,
                                  Integer type, Long userId, Integer isAlert) {
        // 后台暂时不对参数进行验证
        AppUser appUser = AppUser.buildFrom(userId, name, chName, email, mobile, password, type, isAlert);
        try {
            if (userId == null) {
                appUser.setPassword(SecureUtil.md5(SecureUtil.md5(ConstUtils.USER_MANAGE_PASSWORD)));
                userService.save(appUser);
            } else {
                userService.update(appUser);
            }
            write(response, String.valueOf(SuccessEnum.SUCCESS.value()));
        } catch (Exception e) {
            write(response, String.valueOf(SuccessEnum.FAIL.value()));
            logger.error(e.getMessage(), e);
        }
        return null;
    }


    /**
     * 删除用户
     *
     * @param userId
     * @return
     */
    @RequestMapping(value = "/delete")
    public ModelAndView doDeleteUser(Long userId) {
        userService.delete(userId);
        return new ModelAndView("redirect:/manage/user/list");
    }

    /**
     * 用户列表
     */
    @RequestMapping(value = "/list")
    public ModelAndView doUserList(Model model, String searchChName) {
        List<AppUser> users = userService.getUserList(searchChName);
        model.addAttribute("users", users);
        model.addAttribute("searchChName", searchChName);
        model.addAttribute("userActive", SuccessEnum.SUCCESS.value());
        return new ModelAndView("manage/user/list");
    }

    @RequestMapping(value = "/addAuditStatus")
    public ModelAndView doAddAuditStatus(HttpServletRequest request, HttpServletResponse response, Integer status, Integer type, Long appAuditId, String refuseReason) {
        AppAudit appAudit = appService.getAppAuditById(appAuditId);
        AppUser appUser = userService.get(appAudit.getUserId());
        // 通过或者驳回并记录日志
        appService.updateUserAuditStatus(appAuditId, status, appUser.getId());

        // 记录驳回原因
        if (AppCheckEnum.APP_REJECT.value().equals(status)) {
            appAudit.setRefuseReason(refuseReason);
            appService.updateRefuseReason(appAudit, getUserInfo(request));
            userService.delete(appUser.getId());
        }

        // 发钉钉通知
        if (AppCheckEnum.APP_PASS.value().equals(status) || AppCheckEnum.APP_REJECT.value().equals(status)) {
            if (Objects.nonNull(type)) {
                if (type == 1) {
                    appUser.setType(AppUserTypeEnum.SM_ADMIN_USER.value());
                }
                if (type == 2) {
                    appUser.setType(AppUserTypeEnum.REGULAR_USER.value());
                }
                if (type == 0) {
                    appUser.setType(AppUserTypeEnum.ADMIN_USER.value());
                }
            }
            appAudit.setStatus(status);
            userService.update(appUser);
            appDingTalkUtil.noticeUserResult(appUser, appAudit, appUser.getType() == 1 ? "应用管理员" : (appUser.getType() == 2 ? "普通用户" : "管理员"));
        }

        // 批准成功直接跳转
        if (AppCheckEnum.APP_PASS.value().equals(status)) {
            return new ModelAndView("redirect:/manage/app/auditList");
        }

        write(response, String.valueOf(SuccessEnum.SUCCESS.value()));
        return null;
    }

}
